import request from '@/utils/request';

/**
 * 表格配置数据结构
 */
export interface TableConfigRecord {
  id: string;
  tenantId?: string | null;
  code: string;
  name: string;
  description?: string;
  tableName: string;
  apiPath: string;
  fields: any[];
  actions?: {
    create?: boolean;
    update?: boolean;
    delete?: boolean;
    batchDelete?: boolean;
    export?: boolean;
    import?: boolean;
  };
  tableProps?: any;
  permissions?: any;
  status: boolean;
  createdAt: string;
  updatedAt: string;
}

/**
 * 动态表格配置API
 */

// 获取表格配置列表
export async function getTableConfigs(params?: {
  page?: number;
  pageSize?: number;
  name?: string;
  code?: string;
  search?: string;
  status?: boolean;
}) {
  return request.get('/table-configs', { params });
}

// 根据code获取表格配置
export async function getTableConfigByCode(code: string): Promise<TableConfigRecord> {
  const response = await request.get<any>(`/table-configs/code/${code}`);
  console.log('getTableConfigByCode response:', response);
  console.log('response.data:', response.data);
  console.log('response.data.success:', response.data?.success);
  console.log('response.data.data:', response.data?.data);
  
  // API 返回格式是 { success: true, data: {...} }
  if (response.data?.success && response.data?.data) {
    return response.data.data;
  }
  
  // 如果响应格式不同，尝试直接返回 data（可能是直接返回配置对象）
  if (response.data && !response.data.success && (response.data as any).id) {
    console.log('Response format is different, returning response.data directly');
    return response.data as unknown as TableConfigRecord;
  }
  
  throw new Error(`Failed to get table config: response data is invalid. Response: ${JSON.stringify(response.data)}`);
}

// 获取单个表格配置
export async function getTableConfig(id: string) {
  return request.get<TableConfigRecord>(`/table-configs/${id}`);
}

// 创建表格配置
export async function createTableConfig(data: Partial<TableConfigRecord>) {
  return request.post('/table-configs', data);
}

// 更新表格配置
export async function updateTableConfig(id: string, data: Partial<TableConfigRecord>) {
  return request.put(`/table-configs/${id}`, data);
}

// 删除表格配置
export async function deleteTableConfig(id: string) {
  return request.delete(`/table-configs/${id}`);
}

// 批量删除表格配置
export async function batchDeleteTableConfigs(ids: string[]) {
  return request.post('/table-configs/batch-delete', { ids });
}

// 导出API对象
export const tableConfigApi = {
  getList: getTableConfigs,
  getByCode: getTableConfigByCode,
  get: getTableConfig,
  create: createTableConfig,
  update: updateTableConfig,
  delete: deleteTableConfig,
  batchDelete: batchDeleteTableConfigs,
};
